<?php
/**
 * 
 *
 * @category   Application_Extensions
 * @package    Paint
 * @copyright  Copyright 2006-2010 Idragonsolution Developments
 * @license    http://idragonsolution.com/
 * @version    $Id: Bootstrap.php 9747 2012-07-26 02:08:08Z Thien $
 * @author     Thien
 */
class Paint_IndexController extends Core_Controller_Action_Standard
{
    public function init()
    {
        // Check auth
        if( !$this->_helper->requireAuth()->setAuthParams('paint', null, 'view')->isValid()) {
          return;
        }
    
        // Get viewer info
        $this->view->viewer     = Engine_Api::_()->user()->getViewer();
        $this->view->viewer_id  = Engine_Api::_()->user()->getViewer()->getIdentity();
        
        $id = $this->_getParam('paint_id', $this->_getParam('id', null));
        if( $id )
        {
          $paint = Engine_Api::_()->getItem('paint', $id);
          if( $paint )
          {
            Engine_Api::_()->core()->setSubject($paint);
          }
        }
        if( !$this->_helper->requireAuth()->setAuthParams('paint', null, 'view')->isValid()) return;
    
    }
    
    public function browseAction()
    {
        $settings = Engine_Api::_()->getApi('settings', 'core');

        // Get params
        switch($this->_getParam('sort', 'recent')) {
          case 'popular':
            $order = 'view_count';
            break;
          case 'recent':
          default:
            $order = 'modified_date';
            break;
        }
    
    
        // Prepare data
        $table = Engine_Api::_()->getItemTable('paint');
        if( !in_array($order, $table->info('cols')) ) {
          $order = 'modified_date';
        }
        
        $select = $table->select()
          ->where("search = 1")
          ->order($order . ' DESC');
    
        $user_id = $this->_getParam('user');
        if ($user_id) $select->where("owner_id = ?", $user_id);
        if ($this->_getParam('category_id')) $select->where("category_id = ?", $this->_getParam('category_id'));
    
        if ($this->_getParam('search', false)) {
          $select->where('title LIKE ? OR description LIKE ?', '%'.$this->_getParam('search').'%');
        }
        
        // Create new array filtering out private albums
        $viewer = Engine_Api::_()->user()->getViewer();
       
    
        $this->view->canCreate = Engine_Api::_()->authorization()->isAllowed('paint', null, 'create');
        
        $paginator = $this->view->paginator = Zend_Paginator::factory($select);
        $paginator->setItemCountPerPage($settings->getSetting('paint_page', 10));
        $paginator->setCurrentPageNumber( $this->_getParam('page') );
        
        $searchForm = new Paint_Form_Search();
        //$searchForm->getElement('sort')->setValue($this->_getParam('sort'));
        $searchForm->getElement('search')->setValue($this->_getParam('search'));
        $category_id = $searchForm->getElement('category_id');
        if ($category_id) {
          $category_id->setValue($this->_getParam('category_id'));
        }
        $this->view->searchParams = $searchForm->getValues();
    
        // Render
        $this->_helper->content
            //->setNoRender()
            ->setEnabled()
            ;
    }
    
    public function viewAction()
    {
          if( !$this->_helper->requireSubject()->isValid() ) return;
    
        $paint = Engine_Api::_()->core()->getSubject('paint');
        $viewer = Engine_Api::_()->user()->getViewer();
    
        // if this is sending a message id, the user is being directed from a coversation
        // check if member is part of the conversation
        $message_id = $this->getRequest()->getParam('message');
        $message_view = false;
        if( $message_id ) {
          $conversation = Engine_Api::_()->getItem('messages_conversation', $message_id);
          if( $conversation->hasRecipient(Engine_Api::_()->user()->getViewer()) ) {
            $message_view = true;
          }
        }
        $this->view->message_view = $message_view;
//        if( !$message_view && 
//            !$this->_helper->requireAuth()->setAuthParams($paint, null, 'view')->isValid() ) {
//          return;
//        }
    
        $this->view->paintTags = $paint->tags()->getTagMaps();
    
        // Check if edit/delete is allowed
        $this->view->can_edit = $can_edit = $this->_helper->requireAuth()->setAuthParams($paint, null, 'edit')->checkRequire();
        $this->view->can_delete = $can_delete = $this->_helper->requireAuth()->setAuthParams($paint, null, 'delete')->checkRequire();
    
        $this->view->viewer_id = $viewer->getIdentity();
        $this->view->rating_count = Engine_Api::_()->paint()->ratingCount($paint->getIdentity());
        $this->view->paint = $paint;
        $this->view->rated = Engine_Api::_()->paint()->checkRated($paint->getIdentity(), $viewer->getIdentity());
        
        if( $paint->category_id ) {
          $this->view->category = Engine_Api::_()->paint()->getCategory($paint->category_id);
        }
        
        $paint->view_count++;
        $paint->save();
        
        // Render
        $this->_helper->content
            //->setNoRender()
            ->setEnabled()
            ;
    }
    
    public function deleteAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $paint = Engine_Api::_()->getItem('paint', $this->getRequest()->getParam('paint_id'));
        if( !$this->_helper->requireAuth()->setAuthParams($paint, null, 'delete')->isValid()) return;
    
        // In smoothbox
        $this->_helper->layout->setLayout('default-simple');
        
        $this->view->form = $form = new Paint_Form_Delete();
    
        if( !$paint )
        {
          $this->view->status = false;
          $this->view->error = Zend_Registry::get('Zend_Translate')->_("Scribl doesn't exists or not authorized to delete");
          return;
        }
    
        if( !$this->getRequest()->isPost() )
        {
          $this->view->status = false;
          $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
          return;
        }
    
        $db = $paint->getTable()->getAdapter();
        $db->beginTransaction();
    
        try
        {
          Engine_Api::_()->getApi('core', 'paint')->deletePaint($paint);
          $db->commit();
        }
    
        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }
    
        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('Scribl has been deleted.');
        return $this->_forward('success' ,'utility', 'core', array(
          'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'manage'), 'paint_general', true),
          'messages' => Array($this->view->message)
        ));
    }
    
    
    public function uploadAction()
    {
        
        // only members can upload recorder
        if( !$this->_helper->requireUser()->checkRequire() ) {
          $session->status = false;
          $session->error = $this->view->translate('Max file size limit exceeded or session expired.');
          return;
        }
    
        // Check method
        if( !$this->getRequest()->isPost() ) {
          $session->status = false;
          $session->error = $this->view->translate('Invalid request method');
          return;
        }
    
        // Check file
        $values = $this->getRequest()->getPost();
        if( empty($values['imageData'])  ) {
          $session->status = false;
          $session->error = $this->view->translate('No file');
          return;
        }
    
        $viewer = Engine_Api::_()->user()->getViewer();
        
        // Process
        $table = Engine_Api::_()->getDbtable('paints', 'paint');
        $db = $table->getAdapter();
        $db->beginTransaction();
        
        try {
          $file = Engine_Api::_()->getApi('core', 'paint')->createPaint($values['imageData']);
          $paint = $table->createRow();
          
          $paint->photo_id  = $file->getIdentity();
          $paint->paint_url = $file->getHref();
          $paint->owner_id = $viewer->getIdentity();
          $paint->search = 0;
          $paint->save();
          
          $db->commit();
          
          
          return $this->_helper->json(array('status'=>true,'paint_id'=>$paint->getIdentity()));
        
        } catch(Exception $e ) {
          $db->rollback();
    
         
          return $this->_helper->json(array('status'=> false,'error'=> $e->getMessage()));
          
        }
        
        
    }
    
    public function rateAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $user_id = $viewer->getIdentity();
        
        $rating = $this->_getParam('rating');
        $paint_id =  $this->_getParam('paint_id');
    
        
        $table = Engine_Api::_()->getDbtable('ratings', 'paint');
        $db = $table->getAdapter();
        $db->beginTransaction();
    
        try
        {
          Engine_Api::_()->paint()->setRating($paint_id, $user_id, $rating);
             
          $paint = Engine_Api::_()->getItem('paint', $paint_id);
          $paint->rating = Engine_Api::_()->paint()->getRating($paint->getIdentity());
          $paint->save();
    
          $db->commit();
        }
    
        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }
    
        $total = Engine_Api::_()->video()->ratingCount($paint->getIdentity());
    
        $data = array();
        $data[] = array(
          'total' => $total,
          'rating' => $rating,
        );
        return $this->_helper->json($data);
        $data = Zend_Json::encode($data);
        $this->getResponse()->setBody($data);
    }
  
  
    public function uploadInfoAction(){
        // only members can upload recorder
        $data = array();
        if( !$this->_helper->requireUser()->checkRequire() ) {
          $data['status'] = false;
          $data['error'] = $this->view->translate('Max file size limit exceeded or session expired.');
          return $this->_helper->json($data);
          
        }
        
        $session = new Zend_Session_Namespace('Recorder_Upload_Info');
        $data['status'] = $session->status;
        $data['error'] = $session->error;
        $data['id']  = $session->recorder_id;
        return $this->_helper->json($data);
    }
    public function indexAction(){
        
    }
    
    public function manageAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireUser()->isValid() ) return;
        $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('paint', null, 'create')->checkRequire();
    
        // Get navigation
        $this->view->navigation = Engine_Api::_()
          ->getApi('menus', 'core')
          ->getNavigation('paint_main', array(), 'paint_main_manage');
    
        // prepare categories
        $this->view->form = $form = new Paint_Form_Search();
        // Populate form
        /*$this->view->categories = $categories = Engine_Api::_()->paint()->getCategories();
        foreach( $categories as $category )
        {
          $form->category->addMultiOption($category->category_id, $category->category_name);
        }
        */
        // Process form
        $form->isValid($this->_getAllParams());
        $values = $form->getValues();
        $values['user_id'] = $viewer->getIdentity();
        //$this->view->category = $values['category'];
    
        $this->view->paginator = $paginator =
          Engine_Api::_()->getApi('core', 'paint')->getPaintsPaginator($values);
    
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('paint.page', 10);
        $this->view->paginator->setItemCountPerPage($items_count);
        
        $this->view->paginator->setCurrentPageNumber( $this->_getParam('page',1) );
    
        // maximum allowed videos
        $this->view->quota = $quota = (int) Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'paint', 'max');
        $this->view->current_count = $paginator->getTotalItemCount();
   }
  
}